<template>
	<view class="wallet">
		<view class="header" v-if="enterpriseId == 0">
			<!-- <u-icon name="arrow-left" size="44" style="position: relative;top: -80rpx;" @click="back"></u-icon> -->
			<view class="u-text-center">
				<view class="u-font-32"><text>我的余额</text></view>
				<view class="u-flex u-m-t-20">
					<view class="u-flex-1">
						<text class="u-font-24">￥</text>
						<text class="u-font-64">{{statistics.balance}}</text>
					</view>
				</view>
			</view>
			<view class="label-box">
				<view class="item">
					<view class="u-font-40"><text class="num">{{formatNumberWithTenThousand(statistics.weightTotal)}}</text></view>
					<view class="u-font-28 u-m-t-20"><text>回收重量(kg)</text></view>
				</view>
				<view class="item">
					<view class="u-font-40"><text class="num">{{formatNumberWithTenThousand(statistics.incomeTotal) || 0}}</text></view>
					<view class="u-font-28 u-m-t-20"><text>累计收益(元)</text></view>
				</view>
				<view class="item">
					<view class="u-font-40"><text class="num">{{formatNumberWithTenThousand(statistics.integralTotal)}}</text></view>
					<view class="u-font-28 u-m-t-20"><text>碳积分</text></view>
				</view>
			</view>
		</view>

		<u-tabs :list="tabsList" :is-scroll="false" active-color="#10beca" :current="tabsCurrent"
			@change="tabschange"></u-tabs>
		<!-- <view class="tabs">
			<view class="item" :class="{'on':current == 0}" @click="clickTabs(0)">
				<text class="u-p-r-10">{{tabsLabel}}</text><u-icon name="arrow-down" size="24"></u-icon>
			</view>
			<view class="item" :class="{'on':current == 1}" @click="clickTabs(1)">
				<text class="u-p-r-10">{{calendarLabel}}</text>
				<u-icon name="arrow-down" size="24"></u-icon>
			</view>
		</view> -->
		<list-filter-panel :placeholder="'单号查询'" @filter-change="filterChange"></list-filter-panel>
		<!-- 余额明细 -->
		<view class="tabs-item" v-if="tabsCurrent == 0">
			<view v-if="billList.length > 0">
				<u-cell-group>
					<u-cell-item v-for="(item,index) in billList" :key="index" :arrow="false">
						<view slot="title">
							<view><text class="u-font-32">{{item.number}}</text></view>
							<!-- <view><text class="u-font-24">{{item.name}}</text></view> -->
							<view><text class="u-font-24 u-tips-color">{{item.createddatetime}}</text></view>
						</view>
						<view><text class="u-font-28">{{item.type}}</text></view>
						<!-- <text v-if="item.type == '充值'" class="u-main-color u-font-32 color-success">+{{item.amount}}</text>
						<text v-if="item.type == '提现'" class="u-main-color u-font-32 color-danger">{{item.amount}}</text>
						<text v-if="item.type == '回收入账'" class="u-main-color u-font-32 color-success">+{{item.amount}}</text>
						<text v-if="item.type == '提现退回'" class="u-main-color u-font-32 color-success">+{{item.amount}}</text>
						<text v-if="item.type == '送店回收'" class="u-main-color u-font-32 color-success">+{{item.amount}}</text> -->
						
						<text v-if="item.type == '回收入账' || item.type == '送店回收' || item.type == '提现退回'" class="u-main-color u-font-32 color-success">+{{item.amount}}</text>
						<text v-else-if="item.type == '积分消耗'" class="u-main-color u-font-32 color-danger">{{item.integral}}<text class="u-font-24">分</text></text>
						<text v-else class="u-main-color u-font-32 color-danger">{{item.amount}}</text>
						<!-- <text>余额：{{item.balance}}</text> -->
					</u-cell-item>
				</u-cell-group>
				<view class="u-p-t-30">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view>
			</view>
			
			<view v-else class="nomore u-p-t-80 u-p-b-40">
				<u-empty text="您还没有相关的余额明细" mode="list"></u-empty>
			</view>
		</view>
		<!-- 提现记录 -->
		<view class="tabs-item" v-if="tabsCurrent == 1">
			<view v-if="recordList.length > 0">
				<u-cell-group>
					<u-cell-item v-for="(item,index) in recordList" :key="index" :arrow="false" @click="reasonShow(item.reason)">
						<view slot="title">
							<view><text class="u-font-32">{{item.number}}</text></view>
							<view><text class="u-font-24 u-tips-color">{{item.examinedate || '未审核'}}</text></view>
						</view>
						<view><text class="u-font-28">{{item.accounttype}}</text></view>
						<text class="u-main-color u-font-32 color-warning">{{item.amount}}元</text>
					</u-cell-item>
				</u-cell-group>
				<!-- <view class="u-p-t-30">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view> -->
			</view>
			<view v-else class="nomore u-p-t-80">
				<u-empty text="您还没有相关的提现记录" mode="list"></u-empty>
			</view>
		</view>
		<!-- 收入构成 -->
		<view class="tabs-item" v-if="tabsCurrent == 2">
			<view v-if="sumByType.type.length > 0">
				<view class="u-flex u-p-30">
					<view class="u-flex-1"><text>共计收入<text class="bold color-warning u-font-28">{{sumByType.onlinecount+sumByType.offlinecount}}</text>笔</text></view>
					<view><text>合计<text class="color-warning u-font-20">¥</text><text class="bold color-warning u-font-28">{{sumByType.amount}}</text></text></view>
				</view>
				<u-cell-group>
					<template v-for="(item,index) in sumByType.type">
						<template v-for="(cell,i) in item.product">
							<!-- <u-cell-item :key="i" v-if="item.departmentid > 0" @click="getDepartmentIncome(item.departmentid)">
								<view slot="title">
									<view><text class="u-font-32">{{item.productname}}</text></view>
									<view><text class="u-font-24 u-tips-color">{{item.createddatetime}}</text></view>
								</view>
								<view class="u-main-color u-font-32 color-success">{{item.amount}}</view>
								<view class="u-main-color u-font-32 color-warning ">{{item.weight}}</view>
							</u-cell-item> -->
							<u-cell-item :arrow="false" :key="i">
								<view slot="title">
									<view><text class="u-font-32">{{cell.name}}</text></view>
									<!-- <view><text class="u-font-24 u-tips-color">{{item.createddatetime}}</text></view> -->
								</view>
								<view class="u-main-color u-font-32 color-success"><text>收入：</text><text class="color-success u-font-20">¥</text>{{cell.amount}}</view>
								<view class="u-main-color u-font-32 color-warning">
									<text>共回收：</text>
									<text v-if="cell.weight > 0">{{cell.weight}}KG</text>
									<text v-if="cell.quantity > 0">{{cell.quantity}}件</text>
								</view>
							</u-cell-item>
						</template>
					</template>
				</u-cell-group>
				<!-- <view class="u-p-t-30">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view> -->
			</view>
			<view v-else class="nomore u-p-t-80">
				<u-empty text="您还没有相关的收入构成记录" mode="list"></u-empty>
			</view>
		</view>
		
		<!-- <view class="navigation-box">
			<view class="navigation">
				<view class="right">
					<u-button class="navbtn u-flex-1" @click="downloadExcel">下载Excel</u-button>
				</view>
			</view>
			<view class="sp"></view>
		</view> -->
		
		<u-select v-model="showSelect" :list="selectList" @confirm="confirmSelect"></u-select>
		<u-calendar v-model="showCalendar" mode="range" active-bg-color="rgb(16,190,202)"
			range-bg-color="rgba(16,190,202,0.13)" range-color="rgb(16,190,202)" @change="calendarDate"></u-calendar>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				// 是否有企业
				enterpriseId: 0, //136
				userType: '用户', //企业，用户
				// timeType:1,
				sumByType:[],//收入构成
				PageIndex: 1,
				PageSize: 10,
				value: '',
				current: 0,
				list: [{
					name: '月账单'
				}, {
					name: '年账单'
				}],
				billList: [], //用户余额明细
				recordList: [], //用户提现记录
				showCalendar: false,
				showSelect: false,
				selectList: [
					{
						label: '全部',
						value: 0,
					},
					{
						label: '本月',
						value: 1,
					},
					{
						label: '本季度',
						value: 2,
					},
					{
						label: '本年',
						value: 3,
					}
				],
				// dateType: 0,
				// startDate: '',
				// endDate: '',
				// tabsLabel: '全部',
				// calendarLabel: '自定义时间',
				key: '',
				// 时间类型
				timeType: 0, //筛选时间类别：0全部，1今日，2昨日，3本月，4上月，5本季度，6上季度，7本年，9自定义时间段
				startDate: '', //开始时间
				endDate: '', //结束时间
				loadStatus: 'nomore',
				// tab切换
				tabsList: [
					{
						name: '余额明细'
					}, 
					{
						name: '提现记录'
					},
					{
					name: '收入构成'
					},
				],
				tabsCurrent: 0,
				// 统计信息
				statistics: {
					balance: 0,
					carbon: 0,
					income: 0,
					regdays: 0,
					weight: 0
				},
			}
		},
		computed: {
			...mapState({
				userdetail: state => state.userdetail,
				websetting: state => state.webSetting
			})
		},
		watch: {
			withdrawal(val) {
				// if(Number(val) > this.statistics.balance){ //超过账户金额不能点击提现按钮
				if (Number(val) > this.websetting.withdrawalsinglelimit && this.way ==
					0) { //当到账方式是微信钱包时,超过后台设置的微信单次提现限额不能点击提现按钮
					this.disabled = true
					this.error = true
				} else {
					this.disabled = false
					this.error = false
				}
				if (Number(val) == 0) {
					this.disabled = true
				}
			}
		},
		// onShow() {
		// 	this.getStatistics()
			
		// },
		onPullDownRefresh() {
			this.billList = []
			this.PageIndex = 1
			this.getBillList(true).then(() => {
				uni.stopPullDownRefresh(); //停止当前页面下拉刷新
			})
		},
		onReachBottom(e) {
			this.reachBottom()
		},
		onLoad(opt){
			// if(opt.enterpriseid){
			// 	this.enterpriseId = opt.enterpriseid
			// 	this.userType = 1
			// }else{
			// 	this.enterpriseId = 0
			// 	this.userType = 2
			// }
			console.log(opt)
			if(opt.enterpriseid){
				this.enterpriseId = opt.enterpriseid
			}
			if(this.enterpriseId > 0){
				this.userType = '企业'
				uni.setNavigationBarTitle({
					title: '查看其他账户记录'
				})
			}else{
				this.userType = '用户'
			}
			
			this.getBillList()
			this.getStatistics().then(()=>{
				// // 是企业时显示企业的余额回收量等
				// if(this.enterpriseId > 0){
				// 	let enterpriseList = this.userdetail.bindinfo.enterpriselist
				// 	this.statistics.balance = enterpriseList.find((item)=>item.id == this.enterpriseId).balance
				// 	this.statistics.weight = enterpriseList.find((item)=>item.id == this.enterpriseId).weight
				// 	this.statistics.income = enterpriseList.find((item)=>item.id == this.enterpriseId).balance
				// }
			})
			// this.getMyWallet()
			// this.getMyApplyList()
			// this.getsumByType()
		},
		methods: {
			tabschange(index) {
				this.tabsCurrent = index;
				switch (this.tabsCurrent){
					case 0:
						this.getBillList()
						break;
					case 1:
						this.getMyApplyList()
						break;
					case 2:
						this.getsumByType()
						break;
					default:
						break;
				}
			},
			filterChange(obj){
				console.log('filterChange',obj)
				for(let key in obj){
					this.$set(this,key,obj[key])
				}
				this.tabschange(this.tabsCurrent);
			},
			// 余额明细
			getBillList(renew = true) {
				this.loadStatus = 'loading'
				if (renew) {
					this.PageIndex = 1
				}
			
				return this.$u.post('/Bill/List', {
					PageIndex: this.PageIndex,
					PageSize: this.PageSize,
					Key: this.key,
					timeType: this.timeType, //筛选时间类别：0全部，1今日，2昨日，3本月，4上月，5本季度，6上季度，7本年，9自定义时间段
					startDate: this.startDate, //开始时间
					endDate: this.endDate, //结束时间
					enterpriseId: this.enterpriseId,
					// includeDepartment: true
				}).then((res) => {
					console.log(res.rows)
			
					if (renew) {
						this.billList = res.rows
						if (this.billList.length < this.PageSize) {
							this.loadStatus = 'nomore'
						}
					} else {
						if (res.rows.length > 0) {
							res.rows.forEach((item) => {
								this.billList.push(item)
							})
							if (res.rows.length < this.PageSize) {
								this.loadStatus = 'nomore'
							} else {
								this.loadStatus = 'loadmore'
							}
						} else {
							this.loadStatus = 'nomore'
						}
					}
				})
			},
			// 提现记录
			getMyApplyList() {
				this.recordList = []
				this.$u.post('/WithdrawApply/List', {
					pageIndex: 1,
					pageSize: 999,
					Key: this.key,
					timeType: this.timeType, //筛选时间类别：0全部，1今日，2昨日，3本月，4上月，5本季度，6上季度，7本年，9自定义时间段
					startDate: this.startDate, //开始时间
					endDate: this.endDate, //结束时间
					state: [1,2,3,4,5],
					userType: this.userType,
					relationId: this.enterpriseId,
				}).then((res) => {
					this.recordList = res.rows
				})
			},
			// 收入构成
			getsumByType(){
				this.$u.post('/User/Order/SumByType', {
					PageIndex: this.PageIndex,
					PageSize: this.PageSize,
					Key: this.key,
					timeType: this.timeType, //筛选时间类别：0全部，1今日，2昨日，3本月，4上月，5本季度，6上季度，7本年，9自定义时间段
					startDate: this.startDate, //开始时间
					endDate: this.endDate, //结束时间
					userType: this.userType == '用户'?2:1,
					enterpriseId: this.enterpriseId,
				}).then((res) => {
					this.sumByType = res
				})
			},
			formatNumberWithTenThousand(num) {
				// 检查数字是否有效
				if (isNaN(num)) {
					return 0;
				}
			
				// 如果数字小于10000，则直接返回原数字
				if (num < 10000) {
					return num.toFixed(2).toString();
				}
			
				// 计算数值并保留一位小数
				const value = num / 10000;
				const formattedValue = value.toFixed(2);
			
				// 返回格式化的字符串
				return `${formattedValue}万`;
			},
			reasonShow(text){ //驳回原因
				console.log('text',text)
				if(text == ''){
					return
				}
				uni.showModal({
					title: '备注',
					content: text
				})
			},
			getDepartmentIncome(departmentid){
				uni.navigateTo({
					url: '/pages/my/wallet/incomeDetails/incomeDetails?departmentid='+departmentid
				})
			},
			cash() {
				// #ifdef MP-WEIXIN
				wx.reportEvent("cash", {
					"type": this.userdetail.type,
					"mobile": this.userdetail.mobile,
					"usename": this.userdetail.name,
				})
				// #endif
				uni.navigateTo({
					url: '/pages/my/wallet/cashOut/cashOut'
				})
			},
			back() {
				// uni.switchTab({
				// 	url: '/pages/user/user'
				// })
				uni.navigateBack()
			},
			getStatistics() { //获取统计信息
				return this.$store.dispatch('getDetails').then((res) => {
					this.statistics = {
						weightTotal: res.weighttotal,
						incomeTotal: res.incometotal,
						integralTotal: res.integraltotal,
						balance: res.balancetotal
					}
				})
			},
			goRecord(id) {
				uni.navigateTo({
					url: 'recordDetails/recordDetails?id=' + id
				})
			},
			
			
			confirmSelect(e) {
				console.log(e)
				this.dateType = e[0].value
				this.tabsLabel = e[0].label
				this.current = 0;
				this.calendarLabel = '自定义时间'
				// this.getMyApplyList()
				// this.getStatistics()
				// this.getsumByType()
				// this.getBillList()
				this.tabschange(this.tabsCurrent)
			},
			calendarDate(e) {
				console.log(e)
				this.current = 1
				this.dateType = 4
				this.startDate = e.startDate
				this.endDate = e.endDate
				this.calendarLabel = e.startDate + '至' + e.endDate
				// this.getMyApplyList()
				// this.getStatistics()
				// this.getsumByType()
				// this.getBillList()
				this.tabschange(this.tabsCurrent)
			},
			clickTabs(index) {
				if (index == 0) {
					this.showSelect = true
				} else {
					this.showCalendar = true
				}
			},
			goOrderView() {
				uni.navigateTo({
					url: '/pages/my/order/views/views'
				})
			},
			getMyWallet() {
				this.$u.get('/User/Statistics/all?getBalance=true').then((res) => {
					this.money = res.balance
				})
			},
			reachBottom() {
				this.PageIndex += 1
				this.getBillList(false)
			},
			
			call(phone) {
				uni.makePhoneCall({
					phoneNumber: phone
				})
			},
			// 下载excel
			downloadExcel(){
				const that = this
				wx.request({
					url: this.baseURL+"/Bill/Download",
					method: "POST",
					responseType: "arraybuffer", //此处是请求文件流，必须带入的属性
					header:{
						Authorization:uni.getStorageSync('lifeData').Authorization
					},
					data:{
						PageIndex: this.PageIndex,
						PageSize: this.PageSize,
						dateType: this.dateType,
						startDate: this.startDate,
						endDate: this.endDate
					},
					success: res =>{
						console.log(res.data)
						if(res.statusCode === 200){
							wx.getFileSystemManager().writeFile({
								filepath: wx.env.USER_DATA_PATH + "/余额明细.xlsx",
								data: res.data,
								encoding: "binary", //二进制流文件必须是 binary
								success(res){
									wx.openDocument({
										filePath: wx.env.USER_DATA_PATH + "/余额明细.xlsx",
										showMenu: true,
										success: function (rest) {
											console.log('打开文档成功');
										},
										complete: rest=>{
											wx.showModal({
												title: 'rest',
												content: rest.errMsg
											})
										}
									});
								},
								complete: res=>{
									wx.showModal({
										title: wx.env.USER_DATA_PATH + "/余额明细.xlsx",
										content: res.errMsg
									})
								}
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wallet {
		display: flex;
		flex-direction: column;
		min-height: 70vh;
	}

	.header {
		color: #fff;
		padding: 60rpx 30rpx 120rpx 30rpx;
		margin-bottom: 10rpx;
		/* #ifdef MP-WEIXIN */
		// padding-top: calc(44px + 60rpx + var(--status-bar-height));
		/* #endif */
		// border-bottom-right-radius: 60rpx;
		background-color: $u-color-main;
		position: relative;
		margin-bottom: 55px;

		.tips-box {
			.tips-cell {
				border-radius: 10rpx;
			}

			.t-c-small {}
		}

		.btn {
			width: 300rpx;
			height: 80rpx;
			background-color: #fff;
			color: $u-color-main;
			margin: 0 auto;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50rpx;
			font-size: 28rpx;
			margin-top: 50rpx;
			margin-bottom: 20rpx;
		}
	}

	.label-box {
		display: flex;
		background-color: #fff;
		margin: 0 30rpx;
		position: absolute;
		left: 0;
		bottom: -80rpx;
		padding: 30rpx;
		border-radius: 24rpx;
		width: 688rpx;
		// box-shadow: 0px -36rpx 0 #34ac9ad9;

		.item {
			flex: 1;
			text-align: center;
			border-right: 1px solid $u-border-color;
			color: $u-content-color;

			&:last-child {
				border-right: 0;
			}

			.num {
				color: $u-color-red;
				font-weight: bold;
			}
		}
	}

	// 宫格展示
	.grid-box {
		background-color: #fff;
		margin: 0 30rpx;
		padding: 30rpx;
		border-radius: 24rpx;
		margin-top: 30rpx;
	}

	.text-orange {
		color: $u-color-orange;
	}

	.tabs {
		display: flex;
		align-items: center;
		background-color: #fff;
		height: 60rpx;

		.item {
			flex: 1;
			text-align: center;
			font-size: 24rpx;

			&.on {
				color: $u-color-main;
			}
		}
	}
	.bold{
		font-weight: bold;
	}
	.nomore {
		display: flex;
		align-items: center;
		justify-content: center;
		flex: 1;
	}

	.call {
		color: $u-color-main;
	}
	
	// 按钮栏
	.navigation {
		position: fixed;
		bottom: 0;
		width: 100%;
		z-index: 9999;
		// background-color: white;
		display: flex;
		margin-top: 20rpx;
		border: solid 2rpx #f2f2f2;
		background-color: #ffffff;
		
		// padding: 16rpx 0;
		.right {
			display: flex;
			font-size: 28rpx;
			align-items: center;
			flex: 1;
			justify-content: space-around;
			padding-left: 10rpx;
			padding-right: 10rpx;
			padding-top: 20rpx;
			padding-bottom: env(safe-area-inset-bottom);
			.navbtn{
				margin: 0 10rpx;
			}
			.btn {
				line-height: 66rpx;
				padding: 0 30rpx;
				border-radius: 36rpx;
				color: #ffffff;
				margin: 16rpx 0;
			}
		}
	}
	
	.sp{
		// height: calc(185rpx + env(safe-area-inset-bottom));
		height: 205rpx;
		width: 750rpx;
	}
</style>